﻿namespace Baggr.FeedParser.Rss
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    /// <summary>
    /// RSS фид.
    /// </summary>
    [Serializable]
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [XmlRoot("rss", Namespace = "", IsNullable = false)]
    public class RssFeed
        : IFeed
    {
        /// <summary>
        /// Конструктор класса.
        /// </summary>
        public RssFeed()
        {
            Version = "2.0";
        }

        /// <summary>
        /// Непосредственно канал.
        /// </summary>
        [XmlElement("channel", Form = XmlSchemaForm.Unqualified)]
        public RssChannel Channel { get; set; }

        /// <summary>
        /// Версия RSS.
        /// </summary>
        [XmlAttribute("version")]
        public string Version { get; set; }

        /// <summary>
        /// Заглавие ленты.
        /// </summary>
        string IFeed.Title
        {
            get { return Channel.Title; }
        }

        /// <summary>
        /// Ссылка на сайт ленты.
        /// </summary>
        Uri IFeed.Link
        {
            get { return new Uri(Channel.Link); }
        }

        /// <summary>
        /// Описание ленты.
        /// </summary>
        string IFeed.Description
        {
            get { return Channel.Description; }
        }

        /// <summary>
        /// Дата публикации.
        /// </summary>
        DateTime IFeed.PublicationDate
        {
            get
            {
                if (!string.IsNullOrEmpty(Channel.LastBuildDate))
                    return DateTime.Parse(Channel.LastBuildDate);
                if (!string.IsNullOrEmpty(Channel.PubDate))
                    return DateTime.Parse(Channel.PubDate);
                return new DateTime();
            }
        }

        /// <summary>
        /// Изображение фида.
        /// </summary>
        Uri IFeed.ImageUrl
        {
            get
            {
                if (Channel.Image == null)
                    return null;
                if (string.IsNullOrEmpty(Channel.Image.Url))
                    return null;
                return new Uri(Channel.Image.Url);
            }
        }

        /// <summary>
        /// Записи фида.
        /// </summary>
        IEnumerable<IFeedItem> IFeed.Items
        {
            get
            {
                return Channel.Items;
            }
        }
    }
}